using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Ionic.Zip;

public partial class DownloadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(((univNETLib)Session[modzGeneral.mUsu_codigo + "NetLib"]).Idioma);
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(((univNETLib)Session[modzGeneral.mUsu_codigo + "NetLib"]).Idioma);

        string mZIP = "N";
        string mType = "BYTE";
        string mUrl = "";

        try
        { mZIP = Request.QueryString["ZIP"].ToString(); }
        catch (Exception ex)
        { mZIP = "N"; ex.GetType(); }

        try
        { mType = Request.QueryString["TYPE"].ToString(); }
        catch (Exception ex)
        { mType = "BYTE"; ex.GetType(); }

        try
        { mUrl = Request.QueryString["URL"].ToString(); }
        catch (Exception ex)
        { mUrl = ""; ex.GetType(); }

        string mFileName = (string)Session[modzGeneral.mUsu_codigo + "downloadFilename"];
        string mFileNameDownload = mFileName;
        if (mZIP=="S")
            mFileNameDownload = mFileName.Substring(0, mFileName.IndexOf(".")) + ".zip";

        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(mFileNameDownload, System.Text.Encoding.UTF8).Replace("+", "%20"));

        if (mZIP == "S")
        {
            using (ZipFile zip = new ZipFile())
            {
                if (mType == "BYTE")
                    zip.AddEntry(mFileName, (byte[])Session[modzGeneral.mUsu_codigo + "MyData"]);
                else if (mType == "TEXT")
                    zip.AddEntry(mFileName, (string)Session[modzGeneral.mUsu_codigo + "MyData"],System.Text.Encoding.Default);
 
                zip.Save(Response.OutputStream);
            }
        }     
        else
            HttpContext.Current.Response.BinaryWrite((byte[])Session[modzGeneral.mUsu_codigo + "MyData"]);

        Session[modzGeneral.mUsu_codigo + "MyData"] = null;

        if (mUrl != "")
        {
            Server.Transfer(mUrl,false);  
        }
        else
            HttpContext.Current.Response.End();

    }
}
